<template>
  <div v-if="isUseDiyTab" class="tab">
    <div
      v-for="(item, index) in tabs"
      :key="index"
      :class="tabValue === item.name ? 'tab_item tab_item_active' : 'tab_item'"
      @click="toItem(item)"
    >
      {{ item.name }}
    </div>
  </div>
  <n-tabs v-else v-model:value="tabValue" class="tabs_wrapper" v-bind="tabProps">
    <n-tab
      v-for="item in tabs"
      :key="item.id"
      :name="(item as any).name"
      :tab="item.tab"
      @click="toItem(item)"
    >
    </n-tab>
  </n-tabs>
  <slot></slot>
</template>

<script setup lang="ts">
import { TabsProps } from 'naive-ui'
import { AnchorTab } from './types'
import { debounce } from '@/utils'

const props = defineProps<{
  parentId: string
  tabs: Array<AnchorTab.TabItems>
  tabProps?: TabsProps
  isUseDiyTab?: boolean // 是否使用自定应tab，不用则默认使用naiveUI的tab
}>()
let parentDom: any // 父盒子
const tabValue = ref(props.tabs[0].name)

function toItem(item: AnchorTab.TabItems) {
  const { id } = item
  const dom = document.getElementById(id) as HTMLElement
  dom.scrollIntoView({
    behavior: 'smooth'
  })
}

const listenDomIsView = debounce(() => {
  const { scrollTop, scrollHeight, clientHeight } = parentDom
  const isBottom = scrollTop + clientHeight === scrollHeight
  props.tabs.forEach((e) => {
    const dom = document.getElementById(e.id) as HTMLElement
    if (scrollTop >= dom.offsetTop) {
      tabValue.value = e.name
    }
  })
  if (isBottom) {
    tabValue.value = props.tabs[props.tabs.length - 1].name
  }
}, 500)

onMounted(() => {
  parentDom = document.getElementById(props.parentId)
  parentDom.addEventListener('scroll', listenDomIsView)
})

onUnmounted(() => {
  parentDom.removeEventListener('scroll', listenDomIsView)
})

defineExpose({
  toItem
})
</script>

<style lang="less" scoped>
.tabs_wrapper {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 1;
}

.tab {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 9;

  user-select: none;
  width: 100%;
  height: 40px;
  background-color: #f3f3f3;
  display: flex;
  .tab_item {
    cursor: pointer;
    flex: 1;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #333333;
  }
  .tab_item_active {
    color: #1492ff !important;
    font-weight: bold !important;
    background-color: #ffffff;
  }
  .tab_item_active_red {
    width: 6px;
    height: 6px;
    background: #fe5332;
    border-radius: 100%;
    margin-left: 4px;
    display: inline-block;
  }
}
</style>
